import initRequest from './request'
import { useAuthStore } from '@/stores/modules/auth.js'
import { ElMessage } from 'element-plus'
import router from '@/router';

/**默认请求工具 */
const defaultUrl = import.meta.env.MODE == 'development' ? import.meta.env.VITE_APP_PROXY_ORIGIN : ''

export const http = initRequest({
  baseUrl: defaultUrl + import.meta.env.BASE_URL,
  withCredentials: true,
  responseHook: (response) => {
    // 未登录前往登录页面
    if(response.status == '401') {
      const authStore = useAuthStore()
      authStore.cleanAuthInfo()
      window.open(router.resolve(`/Home/Login?return_url=${window.location.href}`).href, "_self")
    } else if(response.status != 200) {
      ElMessage.error('请求失败')
    }
    return response.data
  },
  responseErrorHook: (error) => {
    // 未登录前往登录页面
    if(error.response.status == '401') {
      const authStore = useAuthStore()
      authStore.cleanAuthInfo()
      window.open(router.resolve(`/Home/Login?return_url=${window.location.href}`).href, "_self")
    }
  }
})

/**调取用户信息工具 */
const authtUrl = import.meta.env.PROD ? import.meta.env.VITE_APP_BACKEND_ORIGIN : ''
export const authHttp = initRequest({
  baseUrl: authtUrl
})
